<template>
  <div class="app-container">
    <h2 class="con-title">订单详情</h2>
    <div class="detail-btn-box">
      <el-button type="primary" v-if="(list.orderStatus==1||list.orderStatus==2)&&list.orderStockStatus!='0'" @click="handleModifyStatus('0')">标记无货</el-button>
      <el-button type="primary" v-if="(list.orderStatus==1||list.orderStatus==2)&&list.orderStockStatus!='1'" @click="handleModifyStatus('1')">取消无货</el-button>
      <el-button type="primary" v-if="list.orderStatus==2" @click="delivery">发货</el-button>
      <el-button type="primary" v-if="list.orderStatus==3" @click="logistics">查看物流</el-button>
    </div>
    <div class="tabel-index">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-title">订单基础信息</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">订单编号</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left">{{list.orderCode}}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">订单状态</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left" style="color:#F00;">{{list.orderStatus|formatStatus}}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">下单时间</div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content grid-left" v-if="list.orderCreateDate!=null">{{list.orderCreateDate|formatDate( 'yyyy-MM-dd hh:mm')}}</div>
          <div class="grid-content grid-left" v-else></div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content">支付时间</div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content grid-left" v-if="list.orderPayDate!=null">{{list.orderPayDate|formatDate( 'yyyy-MM-dd hh:mm')}}</div>
          <div class="grid-content grid-left" v-else></div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">发货时间</div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content grid-left" v-if="list.orderLogisDate!=null">{{list.orderLogisDate|formatDate( 'yyyy-MM-dd hh:mm')}}</div>
          <div class="grid-content grid-left" v-else></div>
        </el-col>
        <el-col :span="4">
          <div class="grid-content">完成时间</div>
        </el-col>
        <el-col :span="8">
          <div class="grid-content grid-left" v-if="list.orderConfirmDate!=null">{{list.orderConfirmDate|formatDate( 'yyyy-MM-dd hh:mm')}}</div>
          <div class="grid-content grid-left" v-else></div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">撤销时间</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left" v-if="list.orderRevokeDate!=null">{{list.orderRevokeDate|formatDate( 'yyyy-MM-dd hh:mm')}}</div>
          <div class="grid-content grid-left" v-else></div>
        </el-col>
      </el-row>
    </div>
    <div class="tabel-index">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-title">订单配送信息</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">配送方式</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left">{{list.express}}</div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">配送信息</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left">
            <div style="float:left;width:75%;word-wrap: break-word;" ref="text">{{list.provinceName}} {{list.cityName}} {{list.areaName}} {{list.orderAddress}}， {{list.receiver}}， {{list.orderPhone}} {{list.orderTel}}</div>
            <div style="float:right;margin-right:20px">
              <el-button type="primary" size="mini" plain v-clipboard:copy="message" v-clipboard:success="onCopy">复制</el-button>
              <!--<el-button type="primary" size="mini" plain @click="handleUpdate()">编辑</el-button>-->
            </div>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="4">
          <div class="grid-content">买家留言</div>
        </el-col>
        <el-col :span="20">
          <div class="grid-content grid-left" style="word-wrap: break-word;">{{list.orderRemark}}</div>
        </el-col>
      </el-row>
    </div>
    <div class="tabel-index">
      <el-row>
        <el-col :span="24">
          <div class="grid-content bg-title">订单商品信息</div>
        </el-col>
      </el-row>
      <el-table :data="orderGoodsList" v-loading.body="listLoading" stripe element-loading-text="Loading" border highlight-current-row>
        <el-table-column align="center" label='商品' min-width="200px">
          <template slot-scope="scope">
            <div class="goods">
              <img :src="scope.row.goodsImg" alt="">
              <div class="right">
                <h3>{{scope.row.goodsName}}</h3>
                <p>商品编号：{{scope.row.goodsCode}}</p>
                <p>规格：{{scope.row.goodsSpec}}</p>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="价格(元)" align="center">
          <template slot-scope="scope">
            {{scope.row.goodsDiscountPrice|numFilter}}
          </template>
        </el-table-column>
        <el-table-column label="数量" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.goodsNum}}</span>
          </template>
        </el-table-column>
        <el-table-column label="小记(元)" align="center">
          <template slot-scope="scope">
            {{scope.row.totalGoodsPrice|numFilter}}
          </template>
        </el-table-column>
        <!--<el-table-column align="center" label='佣金'>
                            <template slot-scope="scope">
                              {{scope.row.sku}}
                            </template>
                          </el-table-column>-->
        <el-table-column align="center" label='订单状态'>
          <template slot-scope="scope">
            {{scope.row.orderGoodsStatus|formatStatus}}
          </template>
        </el-table-column>
        <el-table-column align="center" label='售后状态'>
          <template slot-scope="scope">
            {{scope.row.returnStatus|returnStatus}}
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="foot-detail">
      订单共
      <span style="color:#F00;">{{list.orderGoodsNum}}</span>件商品，销售总计：
      <span style="color:#F00;">¥{{list.orderPayPrice|numFilter}}</span>（含运费 ¥{{list.orderFreight|numFilter}}）
    </div>
    <!--弹出层对话框-->
    <el-dialog title="商品发货" :visible.sync="dialogExpressVisible" width="30%" center>
      <el-form :model="form" :rules="rules" ref="form">
        <el-form-item label="物流单号：" :label-width="formLabelWidth" prop="expressNumber">
          <el-input v-model="form.expressNumber" auto-complete="off" width="200px;"></el-input>
        </el-form-item>
        <el-form-item label="物流公司：" :label-width="formLabelWidth" prop="expressName">
          <el-select v-model="form.expressName" placeholder="请选择物流公司">
            <el-option v-for="item in options" :key="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogExpressVisible = false">取 消</el-button>
        <el-button type="primary" @click="submit('form')">确 定</el-button>
      </div>
    </el-dialog>
    <!--<el-dialog title="商品发货" :visible.sync="dialogAddressVisible" width="30%" center>
            <el-form :model="addressForm" :rules="addressRules" ref="addressForm">
              <el-form-item label="省市区：" :label-width="formLabelWidth" prop="areaSelect">
                <el-cascader :options="optionsAdd" v-model="addressForm.areaSelect" @change="handleChange" placeholder="请选择省市区">
                </el-cascader>
              </el-form-item>
              <el-form-item label="详细地址：" :label-width="formLabelWidth" prop="orderAddress">
                <el-input v-model="addressForm.orderAddress" auto-complete="off" width="200px;"></el-input>
              </el-form-item>
              <el-form-item label="收件人：" :label-width="formLabelWidth" prop="receiver">
                <el-input v-model="addressForm.receiver" auto-complete="off" width="200px;"></el-input>
              </el-form-item>
              <el-form-item label="收件人手机号：" :label-width="formLabelWidth" prop="orderPhone">
                <el-input v-model="addressForm.orderPhone" auto-complete="off" width="200px;"></el-input>
              </el-form-item>
              <el-form-item label="收件人电话：" :label-width="formLabelWidth">
                <el-input v-model="addressForm.orderTel" auto-complete="off" width="200px;"></el-input>
              </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
              <el-button @click="dialogAddressVisible = false">取 消</el-button>
              <el-button type="primary" @click="editSuccess('addressForm')">确 定</el-button>
            </div>
          </el-dialog>-->
  </div>
</template>

<script>
import { getOrderDetails } from '@/api/list'
import { setOrderStockStatus } from '@/api/list'
import { getLogisticsCompany } from '@/api/list'
import { confirmDeliverGoods } from '@/api/list'
import { editOrderReceiveAddress } from '@/api/list'
import validate from '@/utils/el-validate'
// import {
//   regionData,
//   CodeToText,
//   TextToCode
// } from 'element-china-area-data'

export default {
  data() {
    return {
      list: {},
      orderGoodsList: [],
      listLoading: true,
      orderId: this.$route.query.orderId,
      dialogExpressVisible: false,
      dialogAddressVisible: false,
      form: {
        expressNumber: '',
        expressName: ''
      },
      // optionsAdd: regionData,
      addressForm: {
        areaSelect: [],
        receiver: '',
        orderPhone: '',
        orderTel: '',
        provinceName: '',
        cityName: '',
        areaName: '',
        orderAddress: ''
      },
      options: null,
      formLabelWidth: '120px',
      value: '',
      rules: {
        expressNumber: [
          { required: true, message: '请输入物流单号', trigger: 'blur' }
        ],
        expressName: [
          { required: true, message: '请选择物流公司', trigger: 'change' }
        ]
      },
      addressRules: {
        areaSelect: [{
          type: 'array',
          required: true,
          message: '请选择省市区',
          trigger: 'trigger'
        }],
        orderAddress: [
          { required: true, message: '请输入详细地址', trigger: 'blur' }
        ],
        receiver: [
          { required: true, message: '请输入收件人姓名', trigger: 'blur' }
        ],
        orderPhone: [
          { required: true, message: '请输入手机号', trigger: 'blur' }, {
            trigger: 'blur',
            validator: validate('telephone', '请输入正确的手机格式')
          }
        ]
      },
      message: ''
    }
  },
  created() {
    this.fetchData()
  },
  filters: {
    numFilter(value) {
      const realVal = Number(value)
      return realVal.toFixed(2)
    },
    formatStatus: function(val) {
      return val === 1 ? '待付款' : val === 2 ? '待发货' : val === 3 ? '已发货' : val === 4 ? '已完成' : val === 5 ? '交易关闭' : '未知'
    },
    returnStatus(val) {
      return val === 0 ? '' : val === 1 ? '待审核' : val === 2 ? '等待寄回' : val === 3 ? '已寄回' : val === 4 ? '已确认' : val === 5 ? '已拒绝' : val === 6 ? '已撤销' : val === 7 ? '待退款' : val === 8 ? '已退款' : '未知'
    }
  },
  updated() {
    this.message = this.$refs.text.innerText
  },
  methods: {
    showCreatedTimes() {
      this.createdTimes = this.createdTimes + 1
    },
    fetchData() {
      this.listLoading = true
      getOrderDetails({ orderId: this.orderId }).then(res => {
        this.list = res.data.orderDetails
        this.orderGoodsList = res.data.orderDetails.orderGoodsList
        this.listLoading = false
      })
    },
    // 标记取消无货
    handleModifyStatus(status) {
      setOrderStockStatus({ orderId: this.orderId, orderStockStatus: status }).then(res => {
        this.$message({
          message: '操作成功',
          type: 'success'
        })
        this.list.orderStockStatus = status
      })
    },
    // 发货
    delivery() {
      this.dialogExpressVisible = true
      getLogisticsCompany().then(res => {
        this.options = res.data.companyList
      })
    },
    // 确认发货
    submit(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          if (this.list.returnStatus) {
            this.$confirm('订单中的部分商品买家已提交了退款申请，您确认要发货吗?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              confirmDeliverGoods({ orderId: this.orderId, expressName: encodeURI(this.form.expressName), expressNumber: this.form.expressNumber }).then(res => {
                this.$message({
                  type: 'success',
                  message: '确认发货成功!'
                })
                this.dialogExpressVisible = false
                this.fetchData()
              })
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消确认发货'
              })
            })
          } else {
            confirmDeliverGoods({ orderId: this.orderId, expressName: encodeURI(this.form.expressName), expressNumber: this.form.expressNumber }).then(res => {
              this.$message({
                type: 'success',
                message: '确认发货成功!'
              })
              this.dialogExpressVisible = false
              this.fetchData()
            })
          }
        } else {
          return false
        }
      })
    },
    logistics() {
      location.href = 'https://www.kuaidi100.com/chaxun?com=&nu=' + this.list.expressNumber
    },
    // 复制
    onCopy(e) {
      this.$message.success('复制配送信息成功: ' + e.text)
    },
    // 编辑
    // handleUpdate() {
    //   this.addressForm = Object.assign({}, this.list) // copy obj
    //   // 获取省市区转成code
    //   if (this.addressForm.provinceName.length === 2) {
    //     this.addressForm.provinceName = this.addressForm.provinceName + '市'
    //     this.addressForm.cityName = '市辖区'
    //   }
    //   const provinceName = this.addressForm.provinceName.trim()
    //   const cityName = this.addressForm.cityName.trim()
    //   const areaName = this.addressForm.areaName.trim()
    //   // 将地址转换
    //   // console.log(TextToCode[provinceName])
    //   // console.log(TextToCode[provinceName][cityName])
    //   const pvcCode = TextToCode[provinceName]
    //   const cityCode = TextToCode[provinceName][cityName]
    //   if (pvcCode !== undefined && cityCode !== undefined) {
    //     this.addressForm.areaSelect = [
    //       TextToCode[provinceName].code,
    //       TextToCode[provinceName][cityName].code,
    //       TextToCode[provinceName][cityName][areaName].code
    //     ]
    //   } else {
    //     this.addressForm.areaSelect = []
    //   }
    //   // const areaSelect = [
    //   //   pvcCode.code,
    //   //   cityCode.code,
    //   //   areaCode.code
    //   // ]
    //   // this.addressForm.areaSelect = areaSelect
    //   this.dialogAddressVisible = true
    //   this.$nextTick(() => {
    //     this.$refs['addressForm'].clearValidate()
    //   })
    // },
    // handleChange(value) {
    //   // 地区代码转成汉字
    //   this.addressForm.provinceName = CodeToText[value[0]]
    //   this.addressForm.cityName = CodeToText[value[1]]
    //   this.addressForm.areaName = CodeToText[value[2]]
    // },
    // 确认编辑
    editSuccess(form) {
      this.$refs[form].validate((valid) => {
        if (valid) {
          editOrderReceiveAddress({ orderId: this.orderId, provinceName: encodeURI(this.addressForm.provinceName), cityName: encodeURI(this.addressForm.cityName), areaName: encodeURI(this.addressForm.areaName), orderAddress: encodeURI(this.addressForm.orderAddress), receiver: encodeURI(this.addressForm.receiver), orderPhone: this.addressForm.orderPhone, orderTel: this.addressForm.orderTel }).then(res => {
            this.$message({
              message: '编辑成功',
              type: 'success'
            })
            this.fetchData()
            this.dialogAddressVisible = false
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
@import 'src/assets/css/jx-order.scss';
.foot-detail {
  min-height: 40px;
  max-width: 1000px;
  line-height: 40px;
  font-size: 14px;
  text-align: right;
  padding-right: 20px;
  border: 1px solid rgb(228, 228, 228);
  margin-top: 20px;
}

.goods img {
  width: 60px;
  float: left;
  margin-top: 8px;
}

.goods .right {
  float: right;
  width: 80%;
}

.goods .right h3 {
  font-size: 13px;
  color: #333333;
  text-align: left;
  margin: 0;
}

.goods .right p {
  color: #AEAEAE;
  text-align: left;
  margin: 0;
}
</style>